/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gtracker;

import java.io.IOException;
import java.net.*;

/**
 * The Dispatcher class is used to
 * recieve all incoming TCP Connections
 * and then forward them to (@link RequestParser)
 * object ( which is multi-threaded )
 * to serve the clients request.
 * @author Jithesh, Nevil, Saurav, Sajin ,Vineeth
 */
public class Dispatcher implements Runnable {

	/**
	 * Constructor for the (@link Dispatcher).
	 * @param portNum The TCP port on which to listen for incoming requests.
	 * @param maxConn The maximum number of connections that server will
	 * serve at a time. Zero removes this limit.
	 */
	public Dispatcher(int portNum, GalaxiaTrackerUI gtUI, Database tDB){
		portNumber = portNum;
		startListening = false;
        parentTracker = gtUI;

		trackerDB = tDB;
		quit = false;

		listener = new Thread(this,"Listener_Thread" );
		listener.start();
	}

    public GalaxiaTrackerUI getParentTracker() {
        return parentTracker;
    }

	@Override
	public void run() {
		ServerSocket server;
		Socket client;

		try {
			server = new ServerSocket(portNumber);

			while (!quit) {
				if (startListening) {
					client = server.accept();
					System.out.println("Accepted Connection");
					new RequestParser(client, getParentTracker(), trackerDB);
				}
			}
		} catch (IOException iexp) {
			System.err.println("Error Occured " + iexp.getMessage());
		}

	}

	/**
	 * The start function starts listening
	 * on the TCP port set by the constructor
	 * for incoming requests and forwards them
	 * to a (@link RequestParser) object for to
	 * be serverd in parallal, until the stop
	 * method is called.
	 */
	public void start(){
		startListening = true;
	}

	/**
	 * The stop method makes the dispatcher
	 * to stop listening and quit the dispacther.
	 */
	public void stop() {
		startListening = false;
		quit = true;
	}

	protected int portNumber;
	protected boolean startListening;
	protected boolean quit;
	protected Database trackerDB;
	protected Thread listener;
    protected GalaxiaTrackerUI parentTracker;
}
